<?php


namespace app\admin\model;


use app\common\lib\RespCode;
use app\common\model\BaseModel;
use custom\Err;

class UserExperience extends BaseModel {

    /**
     * 列表
     * @param $params
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public static function getList($params) {
        $count = db('user_experience')
            ->count();
        if ($count == 0) {
            $result = [
                'page'    => 1,
                'pageNum' => 1,
                'count'   => 0,
                'data'    => [],
            ];
            return $result;
        } else {
            $data = db('user_experience')
                ->order('is_do asc')
                ->order('last_time desc')
                ->field('id,phone,city_names,last_time,mark,status,is_do,name')
                ->page($params['page'], $params['long'])
                ->select();
            foreach ($data as $k => $v) {
                if ($v['is_do'] == 0) {
                    $data[$k]['is_do'] = '处理';
                } else {
                    $data[$k]['is_do'] = '已处理';
                }
                if ($v['status'] == 0) {
                    $data[$k]['status'] = '其它客户';
                } else {
                    $data[$k]['status'] = '意向客户';
                }
                $data[$k]['last_time'] = date('Y-m-d H:i:s', $data[$k]['last_time']);
            }
            $pageNum = ceil($count / $params['long']);
            $result = [
                'page'    => (int)$params['page'],
                'pageNum' => $pageNum,
                'count'   => $count,
                'data'    => $data,
            ];
            return $result;
        }
    }

    /**
     * 编辑
     * @param $params
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     */
    public static function edit($params) {
        if (mb_strlen(trim($params['name']), 'utf-8') > 30) {
            Err::add('名称长度限制30', RespCode::DATA_ERR);
            return false;
        }
        if (mb_strlen(trim($params['mark']), 'utf-8') > 100) {
            Err::add('备注长度限制100', RespCode::DATA_ERR);
            return false;
        }
        $data = [
            'mark'   => $params['mark'] ?? '',
            'name'   => $params['name'] ?? '',
            'status' => $params['status']
        ];
        $self = self::where('id', $params['id'])->find();
        if ($self['is_do'] == 0) {
            $data['is_do'] = 1;
            $data['do_time'] = time();
        }
        self::where('id', $params['id'])->update($data);
        return true;
    }

}